package edu.tgc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.Filter;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.serializer.ByteArrayRawSerializer;
import org.springframework.integration.ip.udp.UnicastReceivingChannelAdapter;
import org.springframework.messaging.Message;

@Configuration
public class DataReceiveConfigration {

	
    @Bean
    public UnicastReceivingChannelAdapter getUnicastReceivingChannelAdapter() {
    	UnicastReceivingChannelAdapter adapter = new  UnicastReceivingChannelAdapter(4567);
    	adapter.setOutputChannelName("udp");
    	return adapter;
    }
    
    @Transformer(inputChannel="udp",outputChannel="udpString")
    public String transformer(Message<?> message) {
    	return new String((byte[])message.getPayload());
    }
    
    @Filter(inputChannel="udpString",outputChannel="udpFilter")
    public boolean filter(String message) {
    	return message.startsWith("abc");
    }
    

    
   @Router(inputChannel="udpFilter")
    public String routing(String message) {
    	if(message.contains("1")) {
    		return "udpRoute1";
    	}
    	else {
    		return "udpRoute2";
    	}	
    }
    
    
   @ServiceActivator(inputChannel="udpRoute1")
   public void udpMessageHandle(String message) {
   	System.out.println("udp1:" +message);
   }
   
   
    @ServiceActivator(inputChannel="udpRoute2")
    public void udpMessageHandle2(String message) {
    	System.out.println("udp2:" +message);
    }
    
   
	
	
    @Bean
    public TcpNetServerConnectionFactory getServerConnectionFactory() {
    	TcpNetServerConnectionFactory serverConnectionFactory = new TcpNetServerConnectionFactory(1234);
    	serverConnectionFactory.setSerializer(new ByteArrayRawSerializer());
    	serverConnectionFactory.setDeserializer(new ByteArrayRawSerializer());
        serverConnectionFactory.setLookupHost(false);
        return serverConnectionFactory;
    }


    @Bean
    public TcpReceivingChannelAdapter getReceivingChannelAdapter() {
        TcpReceivingChannelAdapter receivingChannelAdapter = new TcpReceivingChannelAdapter();
        receivingChannelAdapter.setConnectionFactory(getServerConnectionFactory());
        receivingChannelAdapter.setOutputChannelName("tcp");
        return receivingChannelAdapter;
    }

    
    @ServiceActivator(inputChannel="tcp")
    public void messageHandle(Message<?> message) {
    	System.out.println(new String((byte[])message.getPayload()));
    }


}
